#!/usr/bin/env python
# -*- coding: utf-8 -*-
#code:utf-8
#
# Copyright(C) 2011 SupDo.com
# Licensed under the GUN License, Version 3.0 (the "License");
# 
# File:        decorator.py
# Author:      KuKei
# Create Date: 2011-09-17
# Description: 装饰器模块
# Modify Date: 2011-09-17

from sd.cms.lib import Params, Result, SDMemCache
from sd.cms.lib.utility import *
from django.http import HttpResponse
from datetime import datetime, timedelta

#功能：用来做函数权限管理的模块
#参数：level权限级别
def powerLevel(level=0):
    def _decorate(method):
        def _wrapper(*args, **kwargs):
            #是否有权限执行被装饰的函数
            isPower = False
            #函数的第一个参数为函数类的实例，这个类的积累中有request对象
            myArgs = args[0]
            if myArgs.request.session.has_key(myArgs.params.POWER):
                powerSeesion = myArgs.request.session[myArgs.params.POWER]
                if powerSeesion['isLogin'] and powerSeesion['user'].power >= level:
                    isPower = True
            if isPower:
                return method(*args, **kwargs)
            else:
                #myPost = myArgs.request.POST
                myArgs.result = Result(False,'您没有权限执行此次操作！','','/',3)
                return myArgs.toSkip()
        return _wrapper
    return _decorate


#功能：用来对页面做缓存之用
def cachePage(key, time=24*60*60):
    def _decorate(method):
        def _wrapper(*args, **kwargs):
            mc = SDMemCache()
            #函数的第一个参数为函数类的实例，这个类的积累中有request对象
            myArgs = args[0]
            if myArgs.request.META['QUERY_STRING'] != '' :
                return method(*args, **kwargs)
            #添加命名空间管理
            sID = kwargs['id'] if isHas(kwargs, 'id') else kwargs['name'] if isHas(kwargs, 'name') else kwargs['field'] if isHas(kwargs, 'field') else -1
            sKey = mc.getLongKey(mc.page_prefix, key, sID)
            cLevel = int(nvl(myArgs.globalinfo.cachelevel, -1))
            if ((key in (Params.ARTICLE, Params.PRODUCT) and cLevel < 1) or (key in (Params.ARTICLELIST, Params.PRODUCTLIST) and cLevel < 2)):
                return method(*args, **kwargs)
            val = mc.get(sKey)
            if val:
                try:
                    response = HttpResponse(str(val[0]))
                    response['Last-Modified'] = val[1]
                    myArgs.rtor = response
                except Exception, e:
                    return method(*args, **kwargs)
            else:
                method(*args, **kwargs)
                mc.set(sKey, (myArgs.rtor.content, datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')), time)
            return myArgs.rtor
        return _wrapper
    return _decorate

#功能：用来对数据做缓存之用
def cacheData(key='', time=24*60*60):
    def _decorate(method):
        def _wrapper(*args, **kwargs):
            mc = SDMemCache()
            #添加命名空间管理
            #有参数的用参数做subKey
            subKey = args[1] if len(args)>1 else '0'
            sKey = mc.getLongKey('data', key, method.func_name+subKey)
            val = mc.get(sKey)
            if not val:
                val = method(*args, **kwargs)
                mc.set(sKey, val, time)
            return val
        return _wrapper
    return _decorate

def cacheTag(key='', time=24*60*60):
    def _decorate(method):
        def _wrapper(*args, **kwargs):
            mc = SDMemCache()
            #添加命名空间管理
            ctx = args[1].dicts[0]
            if int(nvl(ctx['site']['global'].cachelevel,-1)) < 1:
                return method(*args, **kwargs)
            #有参数的用参数做subKey
            subArgs = args[0].args
            sKey = mc.getLongKey(mc.data_prefix, key, '_'.join(subArgs))
            val = mc.get(sKey)
            if not val:
                val = method(*args, **kwargs)
                mc.set(sKey, val, time)
            return val
        return _wrapper
    return _decorate

#功能：用来对基础数据做缓存之用
def cacheBase(key='', time=24*60*60):
    def _decorate(method):
        def _wrapper(*args, **kwargs):
            mc = SDMemCache()
            sKey = mc.getLongKey(mc.base_prefix, key, None)
            val = mc.get(sKey)
            if not val:
                val = method(*args, **kwargs)
                mc.set(sKey, val, time)
            return val
        return _wrapper
    return _decorate

#功能：用来对风格文件数据做缓存之用
def cacheTheme(time=24*60*60):
    def _decorate(method):
        def _wrapper(*args, **kwargs):
            mc = SDMemCache()
            subkey = ''.join(args[1:])
            sKey = mc.getLongKey(mc.theme_prefix, '1', subkey)
            val = mc.get(sKey)
            if not val:
                val = method(*args, **kwargs)
                mc.set(sKey, val, time)
            return val
        return _wrapper
    return _decorate